<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="prodPlanId"
                label="生产计划单"
                :rules="[{ required: true, message: '请选择生产计划单' }]"
                :validate-trigger="['change', 'blur']"
              >
                <ASelect
                  v-model="form.prodPlanId"
                  allow-search
                  placeholder="请选择生产计划单"
                  @change="formEvent('prodPlanChange')"
                >
                  <AOption
                    v-for="(item, index) in productPlanList"
                    :key="index"
                    :label="item.prodPlanCode"
                    :value="item.prodPlanId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="productId" label="产品名称">
                <div>{{ productPlanItem?.productName }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="6">
              <AFormItem field="spec" label="规格">
                <div>{{ productPlanItem?.specModel }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="6">
              <AFormItem field="unit" label="单位">
                <div>{{ productPlanItem?.unit }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="materialQty" label="原材料数量">
                <AInputNumber
                  v-model="form.materialQty"
                  model-event="input"
                  placeholder="原材料数量"
                  hide-button
                  :precision="0"
                  :step="1"
                ></AInputNumber>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="inbounderld" label="入库人员">
                <ASelect v-model="form.inbounderld" placeholder="入库人员" allow-search allow-clear>
                  <AOption
                    v-for="(item, index) in employeeList"
                    :key="index"
                    :label="item.employeeName"
                    :value="item.employeeId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="productQty" label="成品数量">
                <AInputNumber
                  v-model="form.productQty"
                  model-event="input"
                  placeholder="成品数量"
                  hide-button
                  :precision="0"
                  :step="1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="totalLossRate" label="总损耗率">
                <AInputNumber
                  v-model="form.totalLossRate"
                  model-event="input"
                  placeholder="总损耗率"
                  hide-button
                  :precision="1"
                  :step="0.1"
                >
                  <template #suffix> % </template>
                </AInputNumber>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="备注">
                <ATextarea v-model="form.remark" />
              </AFormItem>
            </ACol>
          </ARow>
          <ACard
            v-for="(item, index) in form.detailList"
            :key="index"
            class="card-container"
            size="small"
          >
            <template #extra>
              <ALink @click="editProduct('add')">增加工序</ALink>
              <ALink v-if="form.detailList.length > 1" @click="editProduct('del', index)">
                删除工序
              </ALink>
            </template>
            <ARow :gutter="10">
              <ACol :span="12">
                <AFormItem
                  label="工序名称"
                  :field="`detailList[${index}].processId`"
                  :rules="[{ required: true, message: '请选择工序名称' }]"
                  :validate-trigger="['change', 'input', 'blur']"
                >
                  <ASelect
                    v-model="item.processId"
                    allow-search
                    placeholder="输入工序名称搜索"
                    @change="formEvent('processId', item)"
                  >
                    <AOption
                      v-for="(stockItem, index) in processList"
                      :key="index"
                      :label="stockItem.processName"
                      :value="stockItem.processId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="qty" label="工序数量">
                  <AInputNumber
                    v-model="item.qty"
                    model-event="input"
                    placeholder="数量"
                    hide-button
                    :precision="0"
                    :step="1"
                  />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="lossRate" label="损耗率">
                  <AInputNumber
                    v-model="item.lossRate"
                    model-event="input"
                    placeholder="损耗率"
                    hide-button
                    :precision="1"
                    :step="0.1"
                  >
                    <template #suffix> % </template>
                  </AInputNumber>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="mainDirectorId" label="机长">
                  <ASelect
                    v-model="item.mainDirectorId"
                    placeholder="负责人"
                    allow-search
                    allow-clear
                    @change="formEvent('mainDirectorId', item)"
                  >
                    <AOption
                      v-for="(item, index) in employeeList"
                      :key="index"
                      :label="item.employeeName"
                      :value="item.employeeId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="name" label="辅助人员">
                  <ASelect
                    v-model="item.deputyDirectorIdList"
                    placeholder="负责人"
                    allow-search
                    allow-clear
                    multiple
                    @change="formEvent('deputyDirectorIdList', item)"
                  >
                    <AOption
                      v-for="(item, index) in employeeList"
                      :key="index"
                      :label="item.employeeName"
                      :value="item.employeeId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
            </ARow>
          </ACard>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue'
import { EmployeeResItem, getEmployeeAllList } from '@renderer/api/employee'
import {
  editProFinish,
  getProcessAllList,
  getProductionPlanAllList,
  getProFinishDetail,
  ProcessResItem,
  ProductionFinishReq,
  ProductionFinishResItem,
  ProductionPlanResItem
} from '@renderer/api/productionDep'
import { useMenuState } from '@renderer/store'
import { getArrayItemType } from '@renderer/types/global'
import { isEmpty } from 'lodash-es'

interface Props {
  [key: string]: any
  checkData?: Partial<ProductionFinishResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<ProductionFinishReq>({
  prodPlanCode: '',
  productId: '',
  planQty: 0,
  productQty: 0,
  totalLossRate: 0,
  remark: '',
  materialQty: 0,
  detailList: [
    {
      processId: '',
      qty: 0,
      lossRate: 0,
      mainDirectorId: '',
      mainDirectorName: '',
      deputyDirectorIdList: []
    }
  ]
})
const processList = ref<ProcessResItem[]>([])
const menuParam = useMenuState()
const productPlanList = ref<ProductionPlanResItem[]>([])
const productPlanItem = ref<ProductionPlanResItem>() // 选中的计划单
const employeeList = ref<EmployeeResItem[]>([])

// 获取计划单
const getProductPlan = async () => {
  const res = await getProductionPlanAllList({})
  productPlanList.value = res.data.list
}
// 获取工序
const getProcess = () => {
  getProcessAllList({}).then((res) => {
    processList.value = res.data.list
  })
}
// 获取员工列表
const getEmployee = () => {
  getEmployeeAllList({}).then((res) => {
    employeeList.value = res.data.list
  })
}

// 获取详情
const getDetail = () => {
  getProFinishDetail({ prodFlowId: props.checkData.prodFlowId! }).then((res) => {
    form.value = res.data
    if (form.value.prodPlanId) {
      nextTick(() => {
        hanldeProcess()
      })
    }
    if (isEmpty(form.value.detailList)) {
      form.value.detailList = [
        {
          processId: '',
          qty: 0,
          lossRate: 0
        }
      ]
    }
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.prodFlowId = undefined
          }
          const planInfo = productPlanList.value.find(
            (item) => item.prodPlanId === form.value.prodPlanId
          )
          if (planInfo) {
            form.value.prodPlanCode = planInfo.prodPlanCode
          }
          editProFinish(form.value).then(() => {
            Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        prodPlanCode: '',
        productId: '',
        planQty: 0,
        productQty: 0,
        totalLossRate: 0,
        remark: '',
        detailList: [],
        materialQty: 0
      }
      productPlanItem.value = undefined
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getProductPlan()
      getProcess()
      getEmployee()
      if (['修改', '复制'].includes(attrs.title as string)) {
        getDetail()
      }
      break
    case 'cancel':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        prodPlanCode: '',
        productId: '',
        planQty: 0,
        productQty: 0,
        totalLossRate: 0,
        remark: '',
        materialQty: 0,
        detailList: []
      }
      productPlanItem.value = undefined
      emit('update:visible', false)
      break
    default:
      break
  }
}

// 处理工序
const hanldeProcess = () => {
  productPlanItem.value = productPlanList.value.find(
    (item) => item.prodPlanId === form.value.prodPlanId
  )
  if (!isEmpty(productPlanItem.value)) {
    form.value.productId = productPlanItem.value!.productId
    form.value.detailList = []
    if (!isEmpty(productPlanItem.value.processIdList)) {
      form.value.detailList = productPlanItem.value.processIdList?.map((item) => {
        const temp = processList.value.find((processItem) => processItem.processId === item)
        return {
          processId: item,
          qty: 0,
          lossRate: 0,
          mainDirectorId: temp?.mainDirectorId,
          mainDirectorName: temp?.mainDirectorName,
          deputyDirectorIdList: temp?.deputyDirectorIdList,
          deputyDirectorNameList: temp?.deputyDirectorNameList
        }
      })
    } else {
      form.value.detailList = [
        {
          processId: '',
          qty: 0,
          lossRate: 0
        }
      ]
    }
  }
}
// 表单
const formEvent = (
  type: string,
  detailItem?: getArrayItemType<ProductionFinishReq['detailList']>
) => {
  switch (type) {
    case 'prodPlanChange':
      if (form.value.detailList.every((item) => !item.processId)) {
        hanldeProcess()
      } else {
        Modal.warning({
          title: '警告',
          content: '当前工序非空，重新选择生产计划单会刷新所有工序，是否继续改操作',
          okText: '确认',
          cancelText: '取消',
          simple: false,
          hideCancel: false,
          maskClosable: false,
          closable: false,
          onOk: () => hanldeProcess(),
          onCancel: () => {}
        })
      }
      break
    case 'processId':
      {
        const temp = processList.value.find((item) => item.processId === detailItem?.processId)
        if (temp) {
          detailItem!.mainDirectorId = temp.mainDirectorId
          detailItem!.mainDirectorName = temp.mainDirectorName
          detailItem!.deputyDirectorIdList = temp.deputyDirectorIdList
          detailItem!.deputyDirectorNameList = temp.deputyDirectorNameList
        }
      }
      break
    case 'deputyDirectorIdList':
      detailItem!.deputyDirectorNameList = employeeList.value.flatMap((item) => {
        if (detailItem?.deputyDirectorIdList?.includes(item.employeeId)) {
          return [item.employeeName]
        } else {
          return []
        }
      })
      break
    case 'mainDirectorId':
      detailItem!.mainDirectorName = employeeList.value.find(
        (item) => item.employeeId === detailItem?.mainDirectorId
      )?.employeeName
      break
    default:
      break
  }
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        processId: '',
        qty: 0,
        lossRate: 0,
        mainDirectorId: '',
        mainDirectorName: '',
        deputyDirectorIdList: []
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break

    default:
      break
  }
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}
</style>
